<template>
	<view class="content">
		<!-- 顶部头像和ID  -->
		<view class="user-section">
			<image class="user-bg" src="../../static/images/user-backgroud2.png" mode="aspectFill"></image>
			<view class="user-content">
				<!-- A. 未登录 & 未勾选：普通按钮（不会触发系统弹窗） -->
				<button v-if="!isLoggedIn && !privacyChecked" class="avatar-btn disabledBtn" @click="toastNeedPrivacy"
					hover-class="none">
					<image class="avatar" :src="avatar" mode="aspectFill"></image>
				</button>

				<!-- B. 未登录 & 已勾选：真·获取手机号按钮（此时才渲染 open-type） -->
				<button v-else-if="!isLoggedIn && privacyChecked" class="avatar-btn" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber" :disabled="false" hover-class="none">
					<image class="avatar" :src="avatar" mode="aspectFill"></image>
				</button>

				<!-- C. 已登录：仅展示头像（不可点） -->
				<view v-else class="avatar-static">
					<image class="avatar" :src="avatar" mode="aspectFill"></image>
				</view>

				<view class="id-row">
					<text class="user-id" v-if="userName!==''">ID: {{ userName }}</text>
					<text class="user-id" v-else>点击登入👆</text>
					<image class="copy-icon" src="../../static/icon/copy.png" mode="aspectFill" @click="copyId"
						v-if="userName!==''"></image>
				</view>

				<view class="privacy-row" v-if="!isLoggedIn">
					<checkbox-group @change="onPrivacyChange">
						<label class="privacy-label">
							<checkbox :checked="privacyChecked" />
							<text class="privacy-text">
								我已阅读并同意
								<text class="privacy-link" @click.stop="goPrivacy">《隐私政策》</text>
								和
								<text class="privacy-link" @click.stop="goTerms">《用户协议》</text>
							</text>
						</label>
					</checkbox-group>
				</view>
			</view>
		</view>

		<!-- 发光线不要了，直接去掉即可 -->
		<!-- <view class="glow-line"></view> -->
		<!-- 购买课程横幅 -->
		<view class="promo-banner" @click="navTo('./PaymentPolicyPage/PaymentPolicyPage')">
			<view class="promo-left">
				<text class="promo-title">课程卡 · 限时福利</text>
				<text class="promo-sub">系统课套餐更划算，点此查看详情</text>
			</view>
			<view class="promo-btn">购买课程</view>
		</view>

		<!-- 菜单：改成悬浮网格卡片，一行四个 -->
		<view class="menu-box">
			<!-- <view class="menu-item" @click="navTo('./PaymentPolicyPage/PaymentPolicyPage')">
				<image class="icon" src="../../static/icon/icon_money_select.png" mode="aspectFill"></image>
				<text class="text">购买课程</text>
			</view> -->

			<view class="menu-item" v-if="post.some(p => p.includes('老师'))" @click="native2Attendance">
				<image class="icon" src="../../static/icon/check_icon.png" mode="aspectFill"></image>
				<text class="text">上课签到</text>
			</view>

			<view class="menu-item" v-if="post.some(p => p.includes('老师'))" @click="native2Invite">
				<image class="icon" src="../../static/icon/invite.png" mode="aspectFill"></image>
				<text class="text">发起约课</text>
			</view>

			

			<view class="menu-item" v-if="post.some(p => p.includes('老师'))" @click="native2AllStudent">
				<image class="icon" src="../../static/icon/all_student.png" mode="aspectFill"></image>
				<text class="text">所有学生</text>
			</view>
			
			<view class="menu-item" @click="scan">
				<image class="icon" src="../../static/icon/scan.png" mode="aspectFill"></image>
				<text class="text">扫一扫</text>
			</view>
			
		</view>

		<!-- 底部公司信息 -->
		<view class="footer">
			<text class="footer-text">禾页木本教育咨询有限公司</text></br>
			<text class="footer-text">闽ICP备2025115978号-2X</text>
		</view>
	</view>
</template>


<script>
	import WXBizDataCrypt from "@/common/WXBizDataCrypt.js" // 需要引入
	import api from '@/api/api.js';
	export default {
		data() {
			return {
				avatar: "../../static/avatar/nobody.png", // 默认头像
				userName: "",
				post: [],
				privacyChecked: false,
				skipOnShowOnce: false // ← 用来跳过 onShow
			};
		},
		computed: {
			// ✅ 是否已登录（用于控制隐私行显示/隐藏）
			isLoggedIn() {
				return !!this.userName;
			},
			// ✅ 未勾选则禁用登录按钮
			canLogin() {
				return this.privacyChecked;
			}
		},
		mounted() {
			/* this.getUserInfo(); */
		},
		onShow() {
			if (this.skipOnShowOnce) {
				console.log("扫码返回 → 跳过本次 onShow");
				this.skipOnShowOnce = false;
				return;
			}
			this.getUserInfo();
		},
		methods: {
			// 扫一扫
			scan() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode', 'barCode'],
					success: (res) => {
						let url = res.result || '';
						console.log('扫码原始结果:', url);

						// 保险起见再 decode 一次（跟你 options.q 那套保持一致）
						try {
							url = decodeURIComponent(url);
						} catch (e) {
							console.log('decodeURIComponent 出错，使用原始字符串', e);
						}

						console.log('解码后的 URL:', url);

						// ✅ 只有带 bind 的才认为是绑定学生的二维码
						if (url.includes('/bind')) {
							this.handleBindStudentFromUrl(url);
						} else {
							// 非绑定类二维码的兜底处理（你也可以自定义）
							uni.showModal({
								title: '扫码结果',
								content: url,
								showCancel: false
							});
						}
					},
					fail: (err) => {
						console.log('扫码失败:', err);
						if (!/cancel/.test(err.errMsg || '')) {
							uni.showToast({
								title: '扫码失败，请重试',
								icon: 'none'
							});
						}
					}
				});
			},
			getQueryVariable(url) {
				// url 可能是完整链接，也可能只是 ? 后面的部分
				let query = url;
				const qIndex = url.indexOf('?');
				if (qIndex !== -1) {
					query = url.substring(qIndex + 1);
				}

				const params = {};
				query.split('&').forEach(item => {
					if (!item) return;
					const [key, value] = item.split('=');
					if (key) {
						params[key] = decodeURIComponent(value || '');
					}
				});
				return params;
			},
			// 处理绑定学生逻辑
			handleBindStudentFromUrl(url) {
				const params = this.getQueryVariable(url);

				const studentId = params.studentId;
				const inviterId = params.inviterId;
				const qrGenerateTime = params.qrGenerateTime;

				if (!studentId) {
					uni.showToast({
						title: '二维码缺少 studentId',
						icon: 'none'
					});
					return;
				}

				api.bindStudent({
					studentId,
					inviterId,
					qrGenerateTime
				}).then(res => {
					this.skipOnShowOnce = true;
					if (res.code === 200) {
						uni.showToast({
							title: '绑定成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.msg || '绑定失败',
							icon: 'none'
						});
					}
				}).catch(() => {
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					});
				});
			},
			toastNeedPrivacy() {
				uni.showToast({
					title: '请先勾选并同意隐私政策',
					icon: 'none'
				});
			},

			// 勾选变化（保留你原有写法）
			onPrivacyChange(e) {
				this.privacyChecked = (e?.detail?.value || []).length > 0;
			},
			clear() {
				this.avatar = "../../static/avatar/nobody.png";
				this.userName = "";
				this.post = [];
			},
			// ✅ 勾选变化
			onPrivacyChange(e) {
				// checkbox-group 的 e.detail.value 是数组
				this.privacyChecked = (e?.detail?.value || []).length > 0;
			},

			// ✅ 跳转隐私与协议
			goPrivacy() {
				uni.navigateTo({
					url: '/pages/privacy/privacy'
				});
			},
			goTerms() {
				uni.navigateTo({
					url: '/pages/privacy/terms'
				});
			},
			getUserInfo() {
				var that = this
				api.getUserInfo().then(
					res => {
						if (res.code == 200) {
							this.userName = res.user.userName;
							that.avatar = '../../static/avatar/logo_avatar_green_dark.png';
							this.post = res.post;
						} else {
							this.clear();
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					},
					rej => {
						this.clear();
					}
				);
			},
			native2Attendance() {
				uni.navigateTo({
					url: '../attendanceForm/attendanceForm'
				})
			},
			native2Invite() {
				uni.navigateTo({
					url: '../attendanceForm/inviteStudent'
				})
			},
			native2AllStudent() {
				uni.navigateTo({
					url: '/pages/user/allStudent/allStudent'
				})
			},
			getSession() {
				var that = this
				uni.login({
					provider: 'weixin',
					success(res) {
						console.log(res.code);
						var data = {
							code: res.code,
						};
						api.getSessionId(data).then(
							sessionRes => {
								if (sessionRes.code == 200) {
									console.log(sessionRes.data);
									that.sessionKey = sessionRes.data.session_key;
									that.openid = sessionRes.data.openid;
									// uni.setStorageSync('AppToken', sessionRes.data.token);
									// uni.setStorageSync('user', JSON.stringify(sessionRes.data.user));
									// that.avatar = '../../static/avatar/logo_avatar_green_dark.png';
									// that.getUserInfo();

								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									})
								}

							},
							rej => {}
						);

					}
				})
			},
			/* getPhoneNumber(res) { // 获取手机号
				var that = this
				that.phone_code = res.detail.code // 获得的手机code
				that.phone_encryptedData = res.detail.encryptedData //用于解密
				that.phone_iv = res.detail.iv // 用于解密
				debugger
				that.undecodePhoneCode(res.detail.code, res.detail.encryptedData, res.detail.iv);
			}, */
			checkLogin() {
				if (this.userName != '') {
					return;
				};
				if (!this.privacyChecked) {
					uni.showToast({
						title: '请勾选并同意隐私政策',
						icon: 'none'
					});
					return;
				}
			},
			getPhoneNumber(e) {
				// 双保险：如果 somehow 没勾选也进来了
				if (!this.privacyChecked) {
					uni.showToast({
						title: '请先勾选并同意隐私政策',
						icon: 'none'
					});
					return;
				}
				const {
					code,
					errMsg
				} = e.detail || {};
				if (!code) {
					uni.showToast({
						title: '未授权获取手机号',
						icon: 'none'
					});
					return;
				}
				var that = this
				uni.login({
					provider: 'weixin',
					success(res) {
						console.log(res.code);
						api.setPhoneNumberByOpenID({
							'phoneCode': code,
							"loginCode": res.code
						}).then(res => {
							if (res.code === 200) {
								// 假设后端返回的手机号字段是 phoneNumber
								uni.setStorageSync('AppToken', res.data.token);
								uni.setStorageSync('user', JSON.stringify(res.data.user));
								that.avatar = '../../static/avatar/logo_avatar_green_dark.png';
								that.getUserInfo();
								uni.showToast({
									title: '登入成功',
									icon: 'success'
								});
								// ...这里可继续你的登录绑定逻辑
							} else {
								uni.showToast({
									title: res.msg || '获取失败',
									icon: 'none'
								});
							}
						}).catch(() => {
							uni.showToast({
								title: '网络异常',
								icon: 'none'
							});
						});

					}
				})
				// 直接把 code 发给后端，后端去调用微信接口换手机号

			},

			undecodePhoneCode(phone_code, phone_encryptedData, phone_iv) { // 解密需要appid 会话密钥；然后需要手机号的加密字段
				let pc = new WXBizDataCrypt(this.appid, this.sessionKey);
				let phoneData = pc.decryptData(phone_encryptedData, phone_iv);
				var data = {
					userName: phoneData.phoneNumber,
				};
				var that = this;
				debugger
				// uni.login({
				// 	provider: 'weixin',
				// 	success(loginRes) {
				// 		var data = {
				// 			userName: phoneData.phoneNumber,
				// 			code: loginRes.code,
				// 			openid: that.openid,
				// 		};
				// 		api.loginByWx(data).then(
				// 			res => {
				// 				if (res.code == 200) {
				// 					uni.setStorageSync('perms', JSON.stringify(res.data.perms));
				// 					uni.setStorageSync('AppToken', res.data.token);
				// 					uni.setStorageSync('user', JSON.stringify(res.data.user));
				// 					uni.setStorageSync('menus', JSON.stringify(res.data.menus));
				// 					that.getDicts()
				// 				} else {
				// 					uni.showToast({
				// 						title: res.msg,
				// 						icon: 'none'
				// 					})
				// 				}
				// 			},
				// 			rej => {}
				// 		);
				// 	}
				// })
				return;
			},
			// 复制ID
			copyId() {
				uni.setClipboardData({
					data: this.userName,
					success: () => {
						uni.showToast({
							title: "已复制",
							icon: "success"
						});
					}
				});
			},
			// 跳转
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			}
		}
	};
</script>

<style scoped lang="scss">
	.content {
		min-height: 100vh;
		padding: 10upx 20upx;
		background: linear-gradient(to bottom, #e6f4ea 0%, #fdfaf4 100%);
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.glow-line {
		height: 6rpx;
		width: 100%;
		margin: 20rpx 0;
		border-radius: 6rpx;
		background: linear-gradient(270deg, #88d498, #cceabb, #fcd5ce, #f8edeb);
		background-size: 400% 400%;
		animation: glowMove 6s ease infinite;
	}

	.user-section {
		position: relative;
		width: 100%;
		height: 380rpx;
		overflow: hidden;
		margin-top: 10upx;
		width: calc(100% + 40upx); // 20upx 左 + 20upx 右
		margin-left: -20upx; // 抵消 .content 的左 padding
		margin-right: -20upx; // 可写可不写，主要是视觉对称

		.user-bg {
			position: absolute;
			width: 100%;
			height: 100%;
			left: 0;
			top: 0;
			opacity: 0.1;
			z-index: 0;
		}

		.user-content {
			position: relative;
			z-index: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 100%;

			.avatar-btn {
				background: transparent;
				padding: 0;
				border: none;
				overflow: hidden;
				box-shadow: none;
			}

			.avatar-btn::after {
				border: none !important;
			}

			.avatar {
				width: 120upx;
				height: 120upx;

				margin-top: 50upx;
				border: none;
			}

			.id-row {
				display: flex;
				align-items: center;

				.user-id {
					font-size: 30rpx;
					color: #333;
					font-weight: bold;
				}

				.copy-icon {
					width: 36upx;
					height: 36upx;
				}
			}
		}
	}

	.promo-banner {
		width: 100%;
		margin-top: -40rpx; // 轻轻盖住下面区域一点
		margin-bottom: 20px;
		padding: 24rpx 28rpx;
		border-radius: 24rpx;
		background: linear-gradient(90deg, #ffe68b, #ffc857);
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.12);
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.promo-left {
		display: flex;
		flex-direction: column;
	}

	.promo-title {
		font-size: 30rpx;
		font-weight: 700;
		color: #4a3200;
		margin-bottom: 4rpx;
	}

	.promo-sub {
		font-size: 22rpx;
		color: #5f4b20;
		opacity: 0.9;
	}

	.promo-btn {
		padding: 8rpx 26rpx;
		border-radius: 999rpx;
		background: #ffffff;
		font-size: 24rpx;
		color: #ff8a00;
		font-weight: 600;
	}

	.promo-banner:active {
		transform: scale(0.97);
		opacity: 0.9;
	}

	/* ✅ 菜单改成悬浮网格卡片：稍微盖住上面的 user-section */
	.menu-box {
		width: 100%;
		// margin-top: 5rpx;
		/* 关键：往上提一点，盖住头像区域底部 */
		padding: 24rpx 18rpx 10rpx;
		background: rgba(255, 255, 255, 0.96);
		border-radius: 24rpx;
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		z-index: 2;
	}

	/* 四列网格，每个格子无边框，图标 + 文本垂直居中 */
	.menu-item {
		width: 25%;
		padding: 20rpx 0;
		margin-bottom: 16rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		/* 不要边框 */
		border: none;
		box-shadow: none;
		background: transparent;
	}

	/* 图标小一点圆润感 */
	.menu-item .icon {
		width: 64upx;
		height: 64upx;
		margin-bottom: 10upx;
	}

	/* 文字居中，稍微粗一点 */
	.menu-item .text {
		font-size: 26upx;
		color: #333;
		text-align: center;
	}

	/* 点击态小小缩放一下 */
	.menu-item:active {
		transform: scale(0.94);
		opacity: 0.9;
	}

	.footer {
		margin-top: auto;
		padding: 30upx 0;
		text-align: center;
		width: 100%;
	}

	.footer-text {
		font-size: 26upx;
		color: #999;
	}

	.user-content {

		// …保持你原来的
		.privacy-row {
			margin-top: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.privacy-label {
			display: flex;
			align-items: center;
		}

		.privacy-text {
			margin-left: 12rpx;
			font-size: 24rpx;
			color: #666;
		}

		.privacy-link {
			color: #1aad19; // 微信绿，和小程序调性一致
		}
	}

	.avatar-btn.disabledBtn {
		opacity: 0.5;
	}

	.avatar-static .avatar {
		/* 已登录态下只是展示，不可点 */
	}
</style>